//
//  EmoticonTextView.swift
//  EmoticonKeyboard
//
//  Created by apple on 16/2/29.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {

    func insertEmoticonImage(em: Emoticon) {
        //1.点击空白按钮
        if em.isEmpty {
            print("点击的是空白按钮")
            return
        }
        
        if em.isDelete {
            //回删
            deleteBackward()
            return
        }
        
        //点击的是emoji表情
        if em.code != nil {
            replaceRange(selectedTextRange!, withText: em.emojiStr ?? "")
            
            return
        }
        
        //图片的显示比较难一些
        
        //NSTextAttachment '附件'   类型
        
        let imageText = EmoticonAttachment.emoticonImageToImageText(em, font: font!)
        
        //2.获取当前显示的文本属性文本
        //        let strM = NSMutableAttributedString(string: textView.text)
        let strM = NSMutableAttributedString(attributedString: attributedText)
        //将属性字符串替换对应 选中range
        //2.1 在修改之前先记录选中光标
        let range = selectedRange
        
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        //4.设置属性字符串
        attributedText = strM
        //4.设置完毕之后 恢复光标
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
        //主动调用协议方法 
        self.delegate?.textViewDidChange?(self)
    }
    
    
    
    //将属性文本转换文文本
    func fullText() -> String {
        var strM = String()
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: []) { (dict, range, _) -> Void in
            print(dict)
            print("-----------")
            print(range)
            //需要获取表情模型中的表情文字
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("表情图片")
                print(attachment.chs)
                strM += attachment.chs ?? ""
            } else {
                print("非表情图片")
                let str = (self.text as NSString).substringWithRange(range)
                print(str)
                strM += str
            }
        }
        
        return strM
    }

}
